有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Junit 4在@Mock中的作用域生成方法

如果使用注释@Mock进行模拟,为什么模拟对象在测试类安装后显示为“锁定”,在@producted方法中显示为null

public class MyTest {

   @Rule
   public MockitoRule rule = MockitoJUnit.rule();

   @Rule
   public WeldInitiator weld = WeldInitiator.from(MyTest.class).build();

   //@Mock <-- this wont work. Will be null in the @Produces methods
   private ClassThatSutInjects sutInject= mock(ClassThatSutInjects.class);

   private NeedsTest sut;

   @Before
   public void setup() {
      sut = weld.select(NeedsTest.class).get();
   }

   @Test
   public void doesThisWork() {
      //Arrange
      //Mockito.when(sutInject.multiply(anyInt()))
      // .thenReturn(3);//this has no effect on the mock returned by @Produces

      //Act
      sut.doThis(1234);

      //Assert

  }

  @Produces
  public ClassThatSutInjects mockThatClass() {
      Mockito.when(sutInject.multiply(anyInt())).thenReturn(100);   //<-- this works
      return sutInject;
  }

}

public class NeedsTest {
   @Inject
   ClassThatSutInjects someClass

   public void doThis(int number) {
      return someClass.multiply(number);
   }

}

有两件事困扰着我,我希望有人能帮助我理解:

1)@Mock(带注释的字段)在@Producer方法中为null,但如果使用=Mockito,则初始化。改为mock(xxx.class)。从我收集的信息来看,这与何时执行符号和何时应用@Rule有关。请提供更多详细信息

2)我非常希望能够让mock在不同的测试用例中做不同的事情,但这似乎是不可能的,因为@products方法在mockito时“停留在过去”。当()尚未应用时。如何“安排”公共关系测试用例?拥有一个测试类pr。随着时间的推移,测试用例将变得不可维护。。导致代码混乱

编辑:我发现使我的模拟对象保持静态,可以设置我的模拟对象pr.测试方法。我做了一次调试运行,发现producer返回的对象与jUnit@Test中使用的实例不同——显然@producers是在MyTest类的另一个实例上运行的。。。对我来说仍然没有意义,所以仍然:如果有人有一些知识,请分享


共 (1) 个答案

  1. # 1 楼答案

    正如您已经观察到的,生产者在对象的不同实例上运行

    ^{}(第8.1章生产者方法的范围):

    A producer method does not inherit the scope of the bean that declares the method. There are two different beans here: the producer method, and the bean which declares it. The scope of the producer method determines how often the method will be called, and the lifecycle of the objects returned by the method. The scope of the bean that declares the producer method determines the lifecycle of the object upon which the producer method is invoked.

    使字段保持静态是可行的,但这并不是一个很好的解决方案